package com.yinhe.music.yhmusic.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.hwangjr.rxbus.RxBus;
import com.yinhe.music.event.RxBusEventType;

public class NetworkUtils {

    // 网络监控
    private ConnectivityManager connectivityManager;
    private NetworkInfo info;

    private Context mContext;

    public NetworkUtils(Context context) {

        mContext = context;
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        mContext.registerReceiver(mNetworkBroadcastReceiver, mFilter);
    }

    public void onDestory() {
        if (mNetworkBroadcastReceiver != null) {
            mContext.unregisterReceiver(mNetworkBroadcastReceiver);
            mNetworkBroadcastReceiver = null;
        }
        mContext = null;
    }


    public NetworkInfo getNetWorkInfo() {
        return info;
    }
    private BroadcastReceiver mNetworkBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                Log.i("network", "网络状态已经改变");
                boolean isConnect = false;
                connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
                info = connectivityManager.getActiveNetworkInfo();
                if (info != null && info.isAvailable()) {
                    isConnect = true;
//                    WsManager.getInstance().reconnect();//wify 4g切换重连websocket

                }
                RxBus.get().post(RxBusEventType.Home.NETWORK_CONNECT,(Boolean)isConnect);
            }
        }
    };
}
